package com.tokenplus.thai.utils.analytics.http

import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit

object HttpHelper {

    /** 句柄 */
    private var mHttpPoolExecutor: HttpPoolExecutor? = null

    /** 初始化执行线程 */
    private fun getHttpPoolExecutor(): HttpPoolExecutor? {
        if (mHttpPoolExecutor == null) {
            val availableCoreSize = (Runtime.getRuntime().availableProcessors() / 2)
            val corePoolSize = if (availableCoreSize > 0) availableCoreSize else 1
            println("占用cpu核数：$corePoolSize")

            mHttpPoolExecutor = HttpPoolExecutor(
                corePoolSize = corePoolSize,
                maximumPoolSize = corePoolSize,
                keepAliveTime = corePoolSize.toLong(),
                unit = TimeUnit.SECONDS,
                workQueue = LinkedBlockingDeque()
            ).apply {
                allowCoreThreadTimeOut(true)
            }
        }

        return mHttpPoolExecutor
    }

    /**
     * 保存数据
     *
     * @param targetUrl 目标路径
     * @param body 数据体
     */
    fun postData(targetUrl: String, body: String) {
        getHttpPoolExecutor()?.execute {
            var httpURLConnection: HttpURLConnection? = null;
            try {
                println("targetUrl:$targetUrl")
                println("body:$body")

                httpURLConnection = (URL(targetUrl).openConnection() as HttpURLConnection).apply {
                    setRequestProperty("Connection", "Keep-Alive")
                    setRequestProperty("Charset", "UTF-8")
                    setRequestProperty("Content-Type", "application/json")
//                    setRequestProperty(
//                        "Content-Length",
//                        body.toByteArray().size.toString()
//                    )
                    doOutput = true
                    doInput = true
                    useCaches = false
                    requestMethod = "POST"
                    readTimeout = 180000
                    connectTimeout = 120000
                    outputStream.write(body.toByteArray())
                    outputStream.flush()
                    outputStream.close()
                }

                with(httpURLConnection) {
                    val isSuccess = (responseCode == HttpURLConnection.HTTP_OK)
                    if (isSuccess)
                        println("${responseCode}--${targetUrl}--post success!")
                    else
                        println("${responseCode}--${targetUrl}--post fail!")
                }

            } catch (e: Exception) {
                e.printStackTrace();
                println("post fail! ${e.localizedMessage}")

            } finally {
                httpURLConnection?.let {
                    try {
                        it.inputStream.close();
                        it.disconnect();
                    } catch (e: Exception) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}



